package com.chenzouquan.util.toJson;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.*;
import java.nio.charset.StandardCharsets;


public class CsvToJsonConverter {
    private static String csvFilePath = "path/to/csv/file.csv"; // CSV文件路径
    private static String jsonFilePath = "path/to/json/file.json"; // 要保存的JSON文件路径

    public static String change(String csvFilePath) {
        try {
            jsonFilePath=csvFilePath.replace(".csv",".json");
            // 读取CSV文件内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFilePath), StandardCharsets.UTF_8));

            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();


            // 创建JSON根节点
            ObjectNode jsonObject1 = objectMapper.createObjectNode();
            ArrayNode jsonArray = objectMapper.createArrayNode();

            // 读取CSV文件的列头
            String[] headers = reader.readLine().split(",");

            // 逐行读取CSV文件内容并转换为JSON对象
            String line;
            while ((line = reader.readLine()) != null) {
                String[] values = line.split(",");

                // 创建JSON对象
                ObjectNode jsonObject = objectMapper.createObjectNode();

                // 将CSV的列值添加到JSON对象中
                for (int i = 0; i < headers.length; i++) {
                    String header = headers[i].trim();
                    String value = values[i].trim();
                    jsonObject.put(header, value);
                }

                // 将JSON对象添加到JSON数组中
                jsonArray.add(jsonObject);
            }
            // 将行数据数组添加到JSON对象中
            jsonObject1.set("data", jsonArray);
            // 将JSON数组写入JSON文件
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonFilePath), jsonObject1);

            System.out.println("CSV文件成功转换为JSON");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 删除原文件
        new File(csvFilePath).deleteOnExit();
        return jsonFilePath;
    }
}





